package com.example.config;

import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

@EnableWebSecurity
@Configuration
public class SecurityConfiguration {
    @Bean
    public PasswordEncoder passwordEncoder() {
        System.out.println(new BCryptPasswordEncoder().encode("password"));
        return new BCryptPasswordEncoder();
    }
    @Bean
    public DataSource dataSource(){
        //数据源配置
        return new PooledDataSource("com.mysql.cj.jdbc.Driver",
                "jdbc:mysql://localhost:3306/baima", "root", "123456");
    }
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){  //直接参数得到Bean对象
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        return bean;
    }
    @Bean
    public PersistentTokenRepository tokenRepository(DataSource dataSource){
        JdbcTokenRepositoryImpl repository = new JdbcTokenRepositoryImpl();

//        //在启动项目时在数据库中创建存储记住我信息的表，仅第一次需要，后续不需要
//        repository.setCreateTableOnStartup(true);


        repository.setDataSource(dataSource);
        return repository;
    }
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http,
                                           PersistentTokenRepository repository
                                           ) throws Exception{
         return http
                 .authorizeHttpRequests(auth ->{
                     auth.requestMatchers("/static/**").permitAll();
                     auth.requestMatchers("/").hasAnyRole("user","admin");

                   //  auth.requestMatchers("/").permitAll();
                     auth.anyRequest().hasRole("admin");
                   //  auth.anyRequest().authenticated();

                  })
                 .formLogin(conf -> {
                       conf.loginPage("/login");
                       conf.loginProcessingUrl("/doLogin");
                       conf.defaultSuccessUrl("/");
                       conf.permitAll();
                 })
                 .logout(
                         conf -> {
                             conf.logoutUrl("/doLogout");
                             conf.logoutSuccessUrl("/login");
                             conf.permitAll();
                         }
                 )
                 .csrf(AbstractHttpConfigurer::disable)
                 .rememberMe(conf ->{
                  //   conf.alwaysRemember(flase);
                 //   conf.rememberMeParameter();
                       conf.tokenRepository(repository);
                       conf.tokenValiditySeconds(60*60*24*7);
                 })
                 .build();

    }
}
